package com.ym.livedemo.live

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.ym.livedemo.Constant
import com.ym.livedemo.SystemBarHelper
import com.ym.livedemo.api.BusinessViewModel
import com.ym.livedemo.databinding.ActivityCreateLiveBinding
import com.ym.livedemo.live1.AnchorLiveActivity
import com.ym.livedemo.loge
import com.ym.livedemo.startActivity
import com.ym.livedemo.utils.SPUtils
import splitties.toast.UnreliableToastApi
import splitties.toast.toast


class CreateLiveActivity : AppCompatActivity() {
    private val viewModel by viewModels<BusinessViewModel>()
    private lateinit var viewBinding: ActivityCreateLiveBinding
    @OptIn(UnreliableToastApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = ActivityCreateLiveBinding.inflate(layoutInflater)
        setContentView(viewBinding.root)
        SystemBarHelper.immersiveStatusBar(this, 0f)
        init()
        viewBinding.back.setOnClickListener { onBackPressed() }

        viewBinding.login.setOnClickListener {
            login()
        }

        viewBinding.liveUrl.setOnLongClickListener {
            clip(viewBinding.liveUrl.text.toString())
            false
        }
        viewBinding.getLiveUrl.setOnClickListener {
            if (Constant.TOKEN.isBlank()) {
                toast("请先登录!")
                return@setOnClickListener
            }
            getLiveUrl()
        }

        viewBinding.liveCode.setOnLongClickListener {
            clip(viewBinding.liveCode.text.toString())
            false
        }

        viewBinding.getLiveCode.setOnClickListener {
            if (Constant.TOKEN.isBlank()) {
                toast("请先登录!")
                return@setOnClickListener
            }
            getLiveCode()
        }

        viewBinding.liveEdit.setOnLongClickListener {
            clip(viewBinding.liveEdit.text.toString())
            false
        }

        viewBinding.createLive.setOnClickListener {
            if (viewBinding.liveEdit.text.toString().isBlank()) {
                toast("推流链接不能为空！")
                return@setOnClickListener
            }

            startActivity<AnchorLiveActivity>(AnchorLiveActivity.RTMP_URL to viewBinding.liveEdit.text.toString())
//            startActivity<HardStreamingActivity>(
//                BaseStreamingActivity.DIRECTION to true,
//                BaseStreamingActivity.RTMPADDR to viewBinding.liveEdit.text.toString()
//            )
        }
    }

    private fun clip(content: String) {
        if (content.isBlank()) {
            return
        }
        val cm: ClipboardManager =
            getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val mClipData = ClipData.newPlainText("Label", content)
        cm.setPrimaryClip(mClipData)
        toast("复制成功！")
        Log.e("clip", content )
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        viewBinding.userIdEdit.setText(Constant.UID.toString())
        viewBinding.liveUrl.text = SPUtils.get(this, Constant.LIVE_URL_KEY, "") as String
        viewBinding.liveEdit.setText("${viewBinding.liveUrl.text}?code=${viewBinding.liveCode.text}")
        isLogin()
    }

    private fun isLogin() {
        if (Constant.TOKEN.isNotBlank()) {
            viewBinding.loginUser.visibility = View.VISIBLE
            viewBinding.loginUser.text = "(已登录: ${Constant.UID})"
        }
    }

    @OptIn(UnreliableToastApi::class)
    private fun login() {
        if (viewBinding.userIdEdit.text.toString().isBlank()) {
            toast("请输入用户ID")
            return
        }
        Constant.UID = viewBinding.userIdEdit.text.toString().toInt()
        viewModel.login(
            mapOf(
                Pair("type", 3),
                Pair("username", Constant.USER_NAME),
                Pair("phone", Constant.PHONE),
                Pair("uid", Constant.UID),
                Pair("appKey", Constant.APP_KEY),
                Pair("appSecret", Constant.APP_SECRET),
            )
        ) {
            if (it.code == 0) {
                Constant.TOKEN = it.data.token
                SPUtils.put(this@CreateLiveActivity, Constant.TOKEN_KEY, Constant.TOKEN)
                SPUtils.put(this@CreateLiveActivity, Constant.UID_KEY, Constant.UID)
                loge("用户TOKEN: ${Constant.TOKEN}")
                toast("登录成功!")
                isLogin()

            } else {
                toast(it.msg)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getLiveUrl() {
        viewModel.getLiveUrl { url ->
            viewBinding.liveUrl.text = url
            SPUtils.put(this, Constant.LIVE_URL_KEY, url)
            viewBinding.liveEdit.setText("${viewBinding.liveUrl.text}?code=${viewBinding.liveCode.text}")
            toast("获取推流链接成功!")
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getLiveCode() {
        viewModel.getLiveCode { code ->
            val liveCode = if (code.contains("=")) code.split("=").last() else code
            viewBinding.liveCode.text = liveCode
            viewBinding.liveEdit.setText("${viewBinding.liveUrl.text}?code=${viewBinding.liveCode.text}")
            toast("获取推流码成功!")
        }
    }
}